#include "widget.h"
#include "ui_widget.h"
#include <QFileDialog>
#include <QDebug>
#include <QAudioOutput>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QVoice>

// 参考教程：https://www.bilibili.com/video/BV1Eg411m7WQ
// 参考教程版本：qt6
// 本案例使用qt5.14.1 qtCreator4.11.1
// https://gitee.com/vtor3478/AudioPlayer
// 作者：污钞vtor 邮箱：vtor3478@qq.com


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("VtorAudioPlayer-20230424");

    mediaPlayer = new QMediaPlayer(this);

    mediaPlayer->setVolume(ui->volumeSlider->value());

    // 获取总时长
    connect(mediaPlayer, &QMediaPlayer::durationChanged, this, [=](qint64 duration)
    {
        ui->totalLabel->setText(QString("%1:%2").arg(duration / 1000 / 60, 2, 10, QChar('0')).arg(duration / 1000 % 60, 2, 10, QChar('0')));
        ui->playCourseSlider->setRange(0, duration);
    });
    // 获取当前播放时长
    connect(mediaPlayer, &QMediaPlayer::positionChanged, this, [=](qint64 pos)
    {
        ui->curLabel->setText(QString("%1:%2").arg(pos / 1000 / 60, 2, 10, QChar('0')).arg(pos / 1000 % 60, 2, 10 ,QChar('0')));
        ui->playCourseSlider->setValue(pos);
    });
    // 可拖动进度条进行调整
    connect(ui->playCourseSlider, &QSlider::sliderMoved, mediaPlayer, [=]()
    {
        mediaPlayer->setPosition(ui->playCourseSlider->value());
    });
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_openDirBtn_clicked()
{

    ui->listWidget->clear();
    dir = QFileDialog::getExistingDirectory(this);
    qDebug() << dir;
    QStringList fileTypes;
    fileTypes << "*.mp3" << "*.wav";
    QStringList fileNames = QDir(dir).entryList(fileTypes, QDir::Files | QDir::Readable, QDir::Name);
    ui->listWidget->addItems(fileNames);

    qDebug() << fileNames;
}

void Widget::playIndx(int index)
{
    if (ui->listWidget->count() > 0)
    {
        playIndex %= ui->listWidget->count();
        index %= ui->listWidget->count();
        QString fileFullName = dir + "/" + ui->listWidget->item(index)->text();
        qDebug() << fileFullName;

        mediaPlayer->setMedia(QUrl::fromLocalFile(fileFullName));
        mediaPlayer->play();
    }
}

void Widget::on_listWidget_doubleClicked(const QModelIndex &index)
{
    // 获取完整路径
    playIndex = index.row();
    playIndx(playIndex);

}

void Widget::on_playBtn_clicked()
{
    switch (int(mediaPlayer->state()))
    {
    case QMediaPlayer::PlayingState:
        mediaPlayer->pause();
        break;
    case QMediaPlayer::StoppedState:
    case QMediaPlayer::PausedState:
        mediaPlayer->play();
        break;
    }
}

void Widget::on_stopBtn_clicked()
{
    mediaPlayer->stop();
}

void Widget::on_preSongBtn_clicked()
{
    playIndex--;
    playIndx(playIndex);
}

void Widget::on_nextSongBtn_clicked()
{

    playIndex++;
    playIndx(playIndex);
}

void Widget::on_volumeSlider_sliderMoved(int position)
{
    mediaPlayer->setVolume(position);
}
